<?php
/**
 * 逻辑相关处理公共方法.
 *  */

// 计算顺丰邮费    下版本多商品多订单 将一个订单的多个产品加起来算重量
function calcPostage($product_id, $province, $number, $product_info = null, $postage_info = null)
{
    $number = intval($number);
    if (!$province || 0 == $number || (!$product_info && !$product_id)) {
        return 0;
    }
    $province = str_replace(['省', '市', '自治区'], '', $province);
    if (!$product_info && $product_id) {
        $product_info = \think\Db::name('product')->find($product_id);
    }
    if (!$postage_info) {
        $postage_info = \think\Db::name('postage')->where(['admin_id' => $product_info['admin_id'], 'express_code' => 'SF'])->find();
    }
    $postage_price = 0;
    foreach ($postage_info['table'] as $k => $v) {
        if (false !== strpos($v['area'], $province)) {
            $weight = round($product_info['weight'], 2) * $number;
            if ($weight > 1.1) {
                $postage_price += ceil($weight - 1.1) * $v['continue_weight'] + $v['first_weight'];
            } else {
                $postage_price += $v['first_weight'];
            }
            break;
        }
    }

    return round($postage_price, 2);
}

// 买家自动收货后将钱打给供应商并写财务明细记录(批量)  todo 加入消息队列
function financeDetail($order_list)
{
    $time = time();
    $total_fee = [];
    $admin_info_list = [];
    $mstr = date('Y-m');
    $wxgzh_service = new \wx\WxgzhService();
    foreach ($order_list as $key => $order_info) {
        if ($order_info['settlement_time']) {
            continue;
        }
        foreach ($order_info['product'] as $k => $v) {
            $total_fee_row = [];
            if (array_key_exists($v['admin_id'], $admin_info_list)) {
                $admin_info = $admin_info_list[$v['admin_id']];
            } else {
                $admin_info = \think\Db::name('admin')->field('id,balance')->find($v['admin_id']);
            }
            $total_fee_row['admin_id'] = strval($v['admin_id']);
            $total_fee_row['price'] = round($v['real_supply'], 2);
            $total_fee_row['ct'] = $time;
            $total_fee_row['order_id'] = strval($order_info['id']);
            // 供应商所得 = 供货价加 + 运费
            $admin_info['balance'] = round($admin_info['balance'] + $v['real_supply'] + $v['postage'], 2);
            $total_fee_row['balance'] = $admin_info['balance'];
            $admin_info_list[$v['admin_id']] = $admin_info;
            $total_fee[] = $total_fee_row;
        }
        // 增加帮会销售额
        if ($order_info['gang_id']) {
            $gang_info = \think\Db::name('gang')->where('id', $order_info['gang_id'])->find();
            \think\Db::name('gang')->where('id', $order_info['gang_id'])->update(['sale' => round($gang_info['sale'] + $order_info['total_money'], 2)]);
        }
        // 增加供应商销售额
        if ($order_info['admin_id']) {
            $supplier = \think\Db::name('admin')->where('id', $order_info['admin_id'])->find();
            \think\Db::name('admin')->where('id', $order_info['admin_id'])->update(['sale' => round($supplier['sale'] + $order_info['total_real_supply'], 2)]);
        }
        // 增加小店销售量
        if ($order_info['shop_id']) {
            \think\Db::name('shop')->where('id', $order_info['shop_id'])->setInc('sales', 1);
        }
        //客服提成
        if ($order_info['csid']) {
            $cs_info = \think\Db::name('admin')->find($order_info['csid']);
            if ($cs_info['push_money'] > 0) {
                $cost = round($order_info['gang_supply_cost'] - $order_info['total_real_supply'], 2);
                $cs_push_money = round($cs_info['push_money'] * $cost / 100, 2);
                if ($cs_push_money > 0) {
                    $find = \think\Db::name('cs_push_money')->where(['csid' => $order_info['csid'], 'month' => $mstr])->find();
                    if ($find) {
                        \think\Db::name('cs_push_money')->where(['csid' => $order_info['csid'], 'month' => $mstr])->update(['total' => round($find['total'] + $cs_push_money, 2)]);
                    } else {
                        $row = ['csid' => $order_info['csid'], 'total' => $cs_push_money, 'month' => $mstr, 'ct' => $time];
                        \think\Db::name('cs_push_money')->insert($row);
                    }
                }
            }
        }
        \think\Db::name('order')->where('id', $order_info['id'])->update(['settlement_time' => $time]);

        $buyer_info = \think\Db::name('user')->field('name')->find($order_info['buyer']);
        // 红包改为已结算
        foreach ($order_info['red_packet'] as $kk => $vv) {
            \think\Db::name('red_packet')->where(['user_id' => $vv['user_id'], 'order_id' => $order_info['id'], 'not_open' => 1, 'not_settlemetn' => 1, 'type' => $vv['type']])->update(['not_settlemetn' => 0]);
            $red_user_info = \think\Db::name('user')->field('name,gzh_openid')->find($vv['user_id']);
            if ($red_user_info['gzh_openid']) {
                //发送模板消息 红包到账提醒 给红包得主 公众号推送
                $data = [
                    'first' => ['value' => '您有一个红包已经到账啦！'],
                    'keyword1' => ['value' => strval($buyer_info['name'])],
                    'keyword2' => ['value' => $vv['money'].'元'],
                    'keyword3' => ['value' => strval($vv['type'])],
                    'keyword4' => ['value' => strval(date('Y-m-d H:i:s', time()))],
                    'keyword5' => ['value' => $order_info['id']],
                    'remark' => ['value' => '快快拆开吧~'],
                ];
                $wxgzh_service->sendTemplateMsg($red_user_info['gzh_openid'], '8aOFaGGxXFslTebpS4Y_fcRNAFFJcetY7JrjzNJhMWU', $data, 'pages/index/welcome');
            }
        }
    }
    foreach ($admin_info_list as $a) {
        \think\Db::name('admin')->where('id', $a['id'])->update(['balance' => $a['balance']]);
    }
    if ($total_fee) {
        // bug 有时候订单确认收货 这一步没写进库 测的时候遇到过两次 未找到原因
        \think\Db::name('finance_detail')->insertAll($total_fee);
    }
}

// 自动上架官方产品 todo 加入消息队列
function autoPutaway($product_list = null, $gang_list = null)
{
    if (!$gang_list) {
        $gang_list = \think\Db::name('gang')->where('putaway', 0)->select();
    }
    if (!$product_list) {
        $query = ['classify' => 0, 'sold_out' => 0];
        $product_list = \think\Db::name('product')->field('id,specifications')->where($query)->select();
    }
    $first = [];
    foreach ($gang_list as  $gang_info) {
        foreach ($product_list as  $product_info) {
            // 上架官方产品
            $gang_price = [];
            foreach ($product_info['specifications'] as $value) {
                $row['specifications'] = strval($value['title']);
                $gang_product = \think\Db::name('gang_product')->where(['specifications' => $value['title'],'gang_id' => $gang_info['id'], 'product_id' => $product_info['id']])->find();
                $row['product_id'] = $product_info['id'];
                $row['sold_out'] = 0;
                $row['gang_id'] = $gang_info['id'];
                $row['gang_price'] = $gang_product['gang_price']?round($gang_product['gang_price'], 2):round($value['gang_price'], 2);
                $row['retail_price'] = $gang_product['retail_price']?round($gang_product['retail_price'], 2):round($value['retail_price'], 2);
                if ($gang_product['fans_reward']) {
                    $row['fans_reward'] = round($gang_product['fans_reward'], 2);
                }
                $gang_price[] = $row;
            }
            \think\Db::name('gang_product')->where(['product_id' => $product_info['id'], 'gang_id' => $gang_info['id']])->delete();
            \think\Db::name('gang_product')->insertAll($gang_price);
            if (!$first) {
                $first = $product_info;
            }
        }
        $user_list = \think\Db::name('user')->field('id,name,gzh_openid')->where(['gang_id' => $gang_info['id']])->select();
        $wxgzh_service = new \wx\WxgzhService();
        foreach ($user_list as $user_info) {
            if ($user_info['gzh_openid']) {
                // 发送模板消息 公众号 给客户 每个客户只推一条
                $data = [
                    'first' => ['value' => '您好，您的帮会有新产品上架'],
                    'keyword1' => ['value' => $first['name'].(count($product_list) > 1 ? ' 等'.count($product_list).'件商品' : '')],
                    'keyword2' => ['value' => '上架'],
                    'keyword3' => ['value' => count($product_list) > 1 ? '' : '帮会价为：'.$gang_price[0]['gang_price'].'元，'.round($gang_price[0]['gang_price'] / $product_info['tag_price'] * 10, 1).'折'],
                    'remark' => ['value' => ''],
                ];
                $wxgzh_service->sendTemplateMsg($user_info['gzh_openid'], 'it6PrepEdjCypMbYuuNvVHHp1ydSuNW8XEchoWHT6Gk', $data, 'pages/index/welcome');
            }
        }
    }
}

// 默认好评 todo 加入消息队列
function defaultGoodEvaluate($order_info)
{
    //产品评价
    $data = ['ct' => time()];
    $data['score'] = 5;
    $data['content'] = '默认好评';
    $data['praise'] = 1;
    $data['not_praise'] = 0;
    $data['anonymous'] = 0;
    $data['seller'] = $order_info['seller'];
    $data['buyer'] = $order_info['buyer'];
    $data['product_id'] = $order_info['product_id'];
    $data['order_id'] = $order_info['id'];
    $data['specifications'] = $order_info['specifications'];
    \think\Db::name('evaluate')->insert($data);
    // 修改小店综合评分
    $shop_info = \think\Db::name('shop')->where(['user_id' => $order_info['seller']])->find();
    $shop_info['score'] = ($shop_info['score'] * $shop_info['evaluate_num'] + $data['score']) / ($shop_info['evaluate_num'] + 1);
    \think\Db::name('shop')->where(['user_id' => $order_info['seller']])->update(['score' => $shop_info['score'], 'evaluate_num' => $shop_info['evaluate_num'] + 1, 'sales' => $shop_info['sales'] + 1]);
    // 评价后订单改为交易完成状态
    \think\Db::name('order')->where('id', $order_info['id'])->update(['status' => 10, 'evaluate_time' => time()]);
}

// 待结算金额变动(根据红包变动)
function notSettlemetnChange($order_info, $add = true)
{
    foreach ($order_info['red_packet'] as $kk => $vv) {
        $find = \think\Db::name('user')->field('not_settlemetn')->where(['id' => $vv['user_id']])->find();
        if ($add) {
            // 增加待结算金额
            \think\Db::name('user')->where(['id' => $vv['user_id']])->update(['not_settlemetn' => round($find['not_settlemetn'] + round($vv['money'], 2), 2)]);
        } else {
            // 删除红包
            \think\Db::name('red_packet')->where(['user_id' => $vv['user_id'], 'order_id' => $order_info['id'], 'not_settlemetn' => 1, 'type' => $vv['type']])->delete();

            // 减少待结算金额
            \think\Db::name('user')->where(['id' => $vv['user_id']])->update(['not_settlemetn' => round($find['not_settlemetn'] - round($vv['money'], 2), 2)]);
        }
        // 清理缓存
        cache('api_user_info_'.$vv['user_id'], null);
    }
}
